<template>
    <div class="content">
        <TableLayout form-title="">
            <el-form :model="formInline" :rules="rules" ref="formInline" class="formInline" label-width="100px" label-position="right"  slot="form" v-collapse="true">          
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="所属省">
                            <province v-model="formInline.fProvinceId"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属市">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称">
                             <school v-model="formInline.schoolName" :provinceId="formInline.fProvinceId" :cityId="formInline.fCityId" :areaId="formInline.fAreaId" style="width:100%" @change='schoolChange'></school>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="8">
                        <el-form-item label="学校类型">
                            <el-select v-model="formInline.typeSchool" placeholder="请选择" style="width:100%" >
                                <el-option v-for="item in formInline.dataType" :key="item.pId" :label="item.sName" :value="item.pId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="负责人姓名">
                          <el-popover placement="top-start" trigger="focus" content="字符长度不大于6个">
                              <el-input v-model="formInline.leaderName" placeholder="请输入内容" :maxlength="6" slot="reference"></el-input>
                          </el-popover>    
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">    
                    <el-col :span="8">
                        <el-form-item label="负责人手机号" prop="loginNum">
                             <el-input v-model="formInline.loginNum" placeholder="请输入内容" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit('formInline')">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button  @click="goToAddRole">添加学校</el-button>
                    <el-button  @click="deleteRole">批量删除</el-button>
                </div>
            </div>
            <el-table :data="dataApply" border style="width: 100%"  @selection-change="handleSelectionChange"  ref="multipleTable" v-loading="loading">
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column label="学校名称" align="center"  prop="sName" width="170">
                        <template scope="scope">
                                <span>{{scope.row.sName | isNull}}</span>
                        </template>
                </el-table-column>
                
                <el-table-column label="学校类型" align="center" prop="sPeriodName" width="100">
                        <template scope="scope">
                                <span>{{scope.row.sPeriodName | isNull}}</span>
                        </template>
                </el-table-column>

                <el-table-column label="所属地区" align="center" prop="sProvinceName" >
                        <template scope="scope">
                                <span>{{scope.row.sProvinceName | isNull}}</span>
                        </template>
                </el-table-column>
                
                <el-table-column label="详细地址" align="center" prop="sAddress">
                        <template scope="scope">
                                <span>{{scope.row.sAddress | isNull}}</span>
                        </template>
                </el-table-column>
                
                <el-table-column label="创建时间" align="center" prop="sCreateTime" width="170">
                        <template scope="scope">
                                <span>{{scope.row.sCreateTime | isNull}}</span>
                        </template>
                </el-table-column>
                
                <el-table-column align="center" label="创建人" prop="fCreator">
                        <template scope="scope">
                                <span>{{scope.row.fCreator | isNull}}</span>
                        </template>
                </el-table-column>

                <el-table-column label="负责人信息" align="center" width="110">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="goDetail(scope.row.pId)">详情</el-button>
                    </template>                 
                </el-table-column>
                
                <el-table-column align="center" label="科目" width="90">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="subjectDet(scope.row.pId)">详情</el-button>
                    </template>
                </el-table-column>

                <el-table-column label="其他操作" width="140">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="goToReviseRole(scope.row.pId)">修改</el-button>
                        <el-button type="text" class="btn-success" @click="deleteRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>           
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listQuery.total"
                    :current-page.sync="listQuery.page"
                    :page-sizes="config.pageSizes"
                    :page-size="config.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <subjectDetail :dialog="dialog" v-if="dialog.dialogFormVisible"></subjectDetail>
        <!-- created by cuihd at 20180712 优化批量删除学校 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
import { listSchoolPeriod, batchRemoveSchool, pageSchools, validateSchoolNum, batchRemoveSchoolProgress} from 'api/schoolManage';
import TableLayout from 'components/TableLayout';
import { mapState, mapActions, mapGetters } from 'vuex';
import subjectDetail from './subjectDetail';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from 'components/SchoolClasss/school';

export default{
    components: {TableLayout, subjectDetail, province, city, region, school},
    data() {
        return {
            fProvinceId: '',
            fCityId: '',
            fAreaId: '',
            formInline: {// form表单数据
                leaderName: '',
                fProvinceId: '',
                fAreaId: '',
                fCityId: '',
                loginNum: '',
                schoolName: '',
                schoolId: '',
                typeSchool: '',
                dataType: [],
                schoolNameList: []
            },
            dialog: {
                dialogFormVisible: false,
                pid: ''
            },
            checked: true,
            dataApply: [],
            dataNum: 1, // 表格1显示条数，初始为1
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            loading: true,
            schoolLoading: false,
            multipleSelection: [],
            rules: {
                loginNum: [
                    { pattern: /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))+\d{8})$/, message: '请输入正确的联系方式', trigger: 'blur'}
                ]      
            },
            /**
             * created by cuihd at 20180712
             * 优化批量删除教师
             * 添加相关变量
             */
            dialogTitle: '正在批量删除学校...',
            dialogTimeout: false,
            progress: 0
        }
    },
   
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
        }),
        ...mapGetters([
            'uid'
        ])
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        }
    },
    // 初始化
    created() {
        this.searchFetchData();
        this.getSchoolType();
    },
    
    methods: {
        // 全局获取行数
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除学校
        deleteRole() {
            if (this.multipleSelection.length<=0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的学校!'
                })
            }
            let roleIds = '';
            for (let i=0;i<this.multipleSelection.length;i++) {
                roleIds+=this.multipleSelection[i].pId+','; 
            }
            roleIds=roleIds.substring(0, roleIds.length-1)
            if (roleIds.length == 0) {
                return;
            }
            this.$confirm('此操作将批量删除选中学校, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.loading = true;
                batchRemoveSchool(roleIds).then(res => {
                    // this.searchFetchData();
                    // this.$message({
                    //     type: 'success',
                    //     message: response.data.errorMsg
                    // })
                    /**
                     * created by cuihd at 20180712
                     * 优化批量删除教师
                     * 添加相关变量
                     */
                    let timeStamp = res.data.content.timeStamp;
                    let totalNum = res.data.content.totalNum;
                    this.dialogTitle = '正在批量删除学校...';
                    this.dialogTimeout = true;
                    this.progress = 0;
                    this.batchProgress(timeStamp, totalNum);
                });  
            })
        },

        // created by cuihd at 20180712
        // 轮询接口获取未处理的数量
        batchProgress(timeStamp, totalNum) { // 递归轮询接口
            totalNum = Number(totalNum); // 强转成number类型
            batchRemoveSchoolProgress(timeStamp).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchProgress(timeStamp, totalNum);
                        }, 1000);
                    } else {
                        this.btnLoading = false;
                        this.dialogTitle = '批量删除学校成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.searchFetchData();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量删除失败！',
                        type: 'error'
                    });
                }
                
            }).catch(err => {
                console.log(err);
            })
        },

        // 查询学校类型
        getSchoolType() {
            listSchoolPeriod().then(response => {
                let schoolType = response.data.content;
                let select = {
                    sName: '请选择',
                    pId: ''
                }
                schoolType.unshift(select);
                this.formInline.dataType = schoolType;
            });
        },
         // 获取学校id
        schoolChange(val) {
            this.formInline.schoolId = val
        },
        // 单个删除学校
        deleteRow(rows) {
            let roleIds = rows.pId;
            this.$confirm('确定要删除此学校, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                batchRemoveSchool(roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: response.data.errorMsg
                    })
                });  
            }).catch(() => {
                console.log('1')
            });
        },
        // 分页
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.loading = true;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        },
        // 查询列表                  
        searchFetchData() {
            pageSchools(this.listQuery.page, this.config.pageSize, this.formInline.leaderName, this.formInline.loginNum, this.formInline.fProvinceId, this.formInline.fCityId, this.formInline.fAreaId, this.formInline.schoolId, this.formInline.typeSchool).then(response => {              
                this.dataApply = response.data.content.list;
                this.listQuery.total = response.data.content.pagination.total;
                this.loading = false;  
            });
        },
        // 表单查询
        // onSubmit() {
        //     this.loading = true;
        //     this.searchFetchData();
        // },
        onSubmit(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });
        },

        subjectDet(row) {
            this.dialog.pid = row;
            this.dialog.dialogFormVisible = true;
        },
        // 跳转
        goToAddRole() {
            validateSchoolNum().then(res => {
                this.$router.push('addSchool');
            })
            
        },
        goDetail(row) {
            this.$router.push({path: `leaderInfo/${row}`});
        },
        goToReviseRole(row) {
            this.$router.push({path: `modifySchool/${row}`});
        },
        resetForm() {
            this.$router.push('schoolManages');
        }  

    }
}
</script>
<style lang="scss" scoped>
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    label{
        text-align:left;
    }
    .el-tag{
            margin-left:5px;
            background:#f9f9f9;
            color:#444;
        }
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
    .footer{
            text-align:center;
            margin-top:40px;
        }
    .footer .el-button{
            padding:10px 40px;
        }
}

</style>